import React, { useEffect } from 'react';
import MarkdownIt from 'markdown-it';
import DPlayer from 'dplayer';
import MdEditor, { Plugins } from 'react-markdown-editor-lite';
// import style manually
import 'react-markdown-editor-lite/lib/index.css';
import CouterPlugin from './CouterPlugin';
import parsePlayer from '@/utils/parsePlayer';
// Register plugins if required
// MdEditor.use(YOUR_PLUGINS_HERE);

// Initialize a markdown parser
const mdParser = new MarkdownIt(/* Markdown-it options */);

// Finish!
function handleEditorChange({ html, text }: any) {
    console.log('handleEditorChange', html, text);
}
MdEditor.use(CouterPlugin);
export default function MdEditorPage() {
    useEffect(() => {
        let dPlayers: any[] = [];

        function load(d: any, conf: any) {
            conf.container = d;
            dPlayers.push(new DPlayer(conf));
        }

        let eles = document.getElementsByClassName('dplayer') as any;
        for (let j = 0, k = eles; j < k.length; j += 1) {
            load(k[j], JSON.parse(k[j].dataset.config));
        }

        return () => {
            eles = null;
            for (let i = 0; i < dPlayers.length; i += 1) {
                dPlayers[i].destroy();
            }
            dPlayers = [];
        };
    }, []);

    return (
        <div>
            <MdEditor
                style={{ height: '500px' }}
                renderHTML={(text) => {
                    const rawCode = mdParser.render(text);
                    return parsePlayer(rawCode);
                }}
                onChange={handleEditorChange}
            />
        </div>
    );
}
